<template>
  <div class="page">
    <div class="toolbar">
      <el-form :model="query" inline class="filters">
        <el-form-item label="用户名"><el-input v-model="query.username" placeholder="包含匹配" /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="query.full_name" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="query.email" /></el-form-item>
        <el-form-item label="启用">
          <el-select v-model="query.enabled" placeholder="全部" style="width:100px">
            <el-option :value="undefined" label="全部" />
            <el-option :value="true" label="启用" />
            <el-option :value="false" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="load">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="actions">
        <el-button type="primary" @click="openCreate">创建用户</el-button>
        <el-button @click="load">刷新</el-button>
      </div>
    </div>

    <div class="table-area">
      <el-table :data="users" style="width:100%">
        <el-table-column prop="username" label="用户名" min-width="160" />
        <el-table-column prop="full_name" label="姓名" min-width="140" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="enabled" label="启用" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="320">
          <template #default="{ row }">
            <el-button size="small" type="primary" plain @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" plain @click="remove(row)">删除</el-button>
            <el-button size="small" @click="openAssignRoles(row)">设置角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="showDialog" title="设置用户角色" width="520px" destroy-on-close>
      <div v-loading="rolesLoading">
      <div style="margin-bottom:8px">用户：{{ currentUser?.username }}</div>
      <el-checkbox-group v-model="selectedRoleIds">
        <el-checkbox v-for="r in allRoles" :key="r.id" :label="r.id">{{ r.name }}（{{ r.code }}）</el-checkbox>
      </el-checkbox-group>
      </div>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitAssignRoles">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showCreateDialog" title="创建用户" width="520px" destroy-on-close>
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username"><el-input v-model="createForm.username" /></el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="createForm.password" type="password" @input="onPasswordInput" />
          <div class="pwd-hint">
            <span>密码强度：<span :class="['strength', passwordStrength.level]">{{ passwordStrength.text }}</span></span>
            <span class="rules">至少8位，包含大小写、数字和符号中的任意3类</span>
          </div>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2"><el-input v-model="createForm.password2" type="password" /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="createForm.full_name" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="createForm.email" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="createForm.enabled" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog=false">取消</el-button>
        <el-button type="primary" :loading="createSaving" @click="submitCreate">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showEditDialog" title="编辑用户" width="520px" destroy-on-close>
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名"><el-input v-model="editForm.username" disabled /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="editForm.full_name" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="editForm.email" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="editForm.enabled" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog=false">取消</el-button>
        <el-button type="primary" :loading="editSaving" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
  </template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { api } from '../../api/client'

type User = { id: string; username: string; full_name?: string; email?: string; enabled: boolean }
type Role = { id: string; code: string; name: string }

const users = ref<User[]>([])
const query = ref<{ username?: string; full_name?: string; email?: string; enabled?: boolean | undefined }>({ username: '', full_name: '', email: '', enabled: undefined })

async function load() {
  const params: any = {}
  if (query.value.username) params.username = query.value.username
  if (query.value.full_name) params.full_name = query.value.full_name
  if (query.value.email) params.email = query.value.email
  if (query.value.enabled !== undefined) params.enabled = query.value.enabled
  const resp = await api.get('/users/', { params })
  users.value = resp.data
}

function resetQuery() {
  query.value = { username: '', full_name: '', email: '', enabled: undefined }
}

const showDialog = ref(false)
const saving = ref(false)
const rolesLoading = ref(false)
const currentUser = ref<User | null>(null)
const allRoles = ref<Role[]>([])
const selectedRoleIds = ref<string[]>([])

async function openAssignRoles(row: User) {
  currentUser.value = row
  rolesLoading.value = true
  try {
    const rolesResp = await api.get('/roles/')
    allRoles.value = rolesResp.data
    const ur = await api.get(`/users/${row.id}/roles`)
    selectedRoleIds.value = ur.data.map((r: Role) => r.id)
    showDialog.value = true
  } finally { rolesLoading.value = false }
}

async function submitAssignRoles() {
  if (!currentUser.value) return
  saving.value = true
  try {
    await api.post(`/users/${currentUser.value.id}/roles`, { role_ids: selectedRoleIds.value })
    ElMessage.success('已保存')
    showDialog.value = false
  } finally { saving.value = false }
}

const showCreateDialog = ref(false)
const createSaving = ref(false)
const createForm = ref({ username: '', password: '', password2: '', full_name: '', email: '', enabled: true })
const createFormRef = ref<FormInstance>()
const createRules: FormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePasswordStrength, trigger: 'change' }
  ],
  password2: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePasswordMatch, trigger: 'change' }
  ],
}

function openCreate() {
  createForm.value = { username: '', password: '', password2: '', full_name: '', email: '', enabled: true }
  showCreateDialog.value = true
}

async function submitCreate() {
  if (!createFormRef.value) return
  try {
    await createFormRef.value.validate()
    createSaving.value = true
    await api.post('/users/', { username: createForm.value.username, password: createForm.value.password, full_name: createForm.value.full_name || undefined, email: createForm.value.email || undefined, enabled: createForm.value.enabled })
    ElMessage.success('创建成功')
    showCreateDialog.value = false
    await load()
  } catch (err: any) {
    const msg = err?.response?.data?.detail || err?.message || '创建失败'
    ElMessage.error(msg)
  } finally { createSaving.value = false }
}

function onPasswordInput() {}

function validatePasswordMatch(_: any, value: string, callback: Function) {
  if (value !== createForm.value.password) return callback(new Error('两次输入的密码不一致'))
  callback()
}

function validatePasswordStrength(_: any, value: string, callback: Function) {
  const s = calcPasswordStrength(value, createForm.value.username)
  if (s.score < 2) return callback(new Error('密码强度过低'))
  callback()
}

function calcPasswordStrength(pw: string, username?: string) {
  let score = 0
  const hasLower = /[a-z]/.test(pw)
  const hasUpper = /[A-Z]/.test(pw)
  const hasDigit = /\d/.test(pw)
  const hasSymbol = /[^A-Za-z0-9]/.test(pw)
  const classes = [hasLower, hasUpper, hasDigit, hasSymbol].filter(Boolean).length
  if (pw.length >= 8) score++
  if (pw.length >= 12) score++
  if (classes >= 3) score++
  const allSame = /^([\s\S])\1*$/.test(pw)
  if (allSame) score = 0
  if (username && pw.toLowerCase().includes(username.toLowerCase())) score = Math.max(0, score - 1)
  const text = score >= 3 ? '强' : score === 2 ? '中' : '弱'
  const level = score >= 3 ? 'strong' : score === 2 ? 'medium' : 'weak'
  return { score, text, level }
}

const passwordStrength = computed(() => calcPasswordStrength(createForm.value.password, createForm.value.username))

onMounted(load)

const showEditDialog = ref(false)
const editSaving = ref(false)
const editForm = ref({ id: '', username: '', full_name: '', email: '', enabled: true })
const editFormRef = ref<FormInstance>()
const editRules: FormRules = {
  email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }]
}

function openEdit(row: User) {
  editForm.value = { id: row.id, username: row.username, full_name: row.full_name || '', email: row.email || '', enabled: row.enabled }
  showEditDialog.value = true
}

async function submitEdit() {
  if (!editFormRef.value) return
  try {
    await editFormRef.value.validate()
    editSaving.value = true
    await api.patch(`/users/${editForm.value.id}`, { full_name: editForm.value.full_name || undefined, email: editForm.value.email || undefined, enabled: editForm.value.enabled })
    ElMessage.success('保存成功')
    showEditDialog.value = false
    await load()
  } catch (err: any) {
    const msg = err?.response?.data?.detail || err?.message || '保存失败'
    ElMessage.error(msg)
  } finally { editSaving.value = false }
}

async function remove(row: User) {
  try {
    await ElMessageBox.confirm('确认删除该用户？', '提示', { type: 'warning' })
    await api.delete(`/users/${row.id}`)
    ElMessage.success('删除成功')
    await load()
  } catch (e) { /* 取消或错误均不抛出 */ }
}
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; }
.toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.filters { flex: 1; display: flex; align-items: center; gap: 12px; }
.filters :deep(.el-form-item) { margin-bottom: 0; }
.actions { display: flex; gap: 12px; align-items: center; }
.table-area { flex: 1; min-height: 0; }
.table-area :deep(.el-table__body-wrapper) { height: 100%; overflow: auto; }
.pwd-hint { margin-top: 6px; display: flex; gap: 12px; font-size: 12px; color: var(--el-text-color-secondary); }
.strength { font-weight: 600; }
.strength.weak { color: var(--el-color-error); }
.strength.medium { color: var(--el-color-warning); }
.strength.strong { color: var(--el-color-success); }
</style>
